package com.Sdebruijn.curriculumvitae.util;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

/**
 * Utility class using Java's Reflection in order to extort the FragmentManager
 * since it's API does not meet my needs.
 * 
 * @author Stefan de Bruijn
 * 
 */
// TODO create or find a utility class that will just return a copy of any
// object with everything public instead
public class FragmentManagerUtils {

	/**
	 * Returns the current active {@link Activity} of the
	 * {@link FragmentManager}
	 * 
	 * @param fm
	 * @return
	 */
	public static Activity getFieldmActivity(FragmentManager fm) {
		try {
			@SuppressWarnings("unchecked")
			Class<FragmentManager> cls = (Class<FragmentManager>) fm.getClass();
			Field field = cls.getDeclaredField("mActivity");
			field.setAccessible(true);
			Activity activity = (Activity) field.get(fm);
			return activity;

		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static ArrayList<Fragment> getFieldmActive(FragmentManager fm){
		try {
			Class<FragmentManager> cls = (Class<FragmentManager>) fm.getClass();
			Field field = cls.getDeclaredField("mActive");
			field.setAccessible(true);
			ArrayList<Fragment> activeFragments = (ArrayList<Fragment>) field.get(fm);
			return activeFragments;
			
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

}
